package org.example.servlet;

import org.example.annotation.IAutowired;
import org.example.annotation.IComponent;
import org.example.annotation.MyContext;
import org.example.confirg.SpringConfiguration;
import org.example.factory.BeanFactory;
import org.example.factory.ProxyFactory;
import org.example.pojo.Result;
import org.example.service.TransferService;
import org.example.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "transferServlet", urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

    private TransferService transferService = null;


    @Override
    public void init() throws ServletException {
        System.out.println("--------init-----------");
        try {
            MyContext myContext = new MyContext(SpringConfiguration.class);

            transferService = (TransferService) BeanFactory.getBean("transferService");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {

            // 2. 调用service层方法
            transferService.transfer(fromCardNo, toCardNo, money);
            result.setStatus("200");
        } catch (Exception e) {
            System.out.println("fromCardNo=" + fromCardNo);
            System.out.println("toCardNo=" + toCardNo);
            System.out.println("money=" + money);
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }
}
